import jade.content.lang.sl.SLCodec;
import jade.content.onto.basic.*;

import jade.core.*;
import jade.core.behaviours.*;

import jade.domain.*;
import jade.domain.introspection.*;
import jade.domain.FIPAAgentManagement.*;
import jade.domain.JADEAgentManagement.*;

import jade.lang.acl.*;

import jade.proto.*;

import jade.wrapper.*;

import java.util.*;



public class dataAgent extends Agent
{
	ArrayList <String> jadeContainer;
	Object[] arguments;
	String events[];
	simulationStartUpBehaviour startUp;
	int numberOfAgents;
	long timeStamp;
	String sleepAgentName;
	String sendAgentName;
	String receiveAgentName;
	

	protected void setup()
	{
		arguments = getArguments();
		if(arguments!=null)
		{
			for(int i=0;i<arguments.length;i++)
			{
				System.out.println(String.valueOf(arguments[i]));
			}
		}
		System.out.println(getLocalName() + ": I am a data agent.");

		//Performs registration actions
		initialize();

		//Description used to register with the DF agent
		DFAgentDescription agentDescription = new DFAgentDescription();
		
		//Sets the name used in the description
		agentDescription.setName(getAID());

		//result is used to hold lists of agent descriptions returned from the search	
		DFAgentDescription[] result=new DFAgentDescription [0];
		
		//used to filter results from the search
		DFAgentDescription template = new DFAgentDescription();
		
		//Used to decide what kind of  service you are looking for
		ServiceDescription agentServiceTemplate = new ServiceDescription();
		
		//String description of the Service
		agentServiceTemplate.setType("Master_Data_Agent");
		
		//Add your service template to the template
		template.addServices(agentServiceTemplate);

		try
		{
			//Search for the agent services matching the template
			result = DFService.search(this,template);
			
		}
		catch(FIPAException fe)
		{
			fe.printStackTrace();
		}
		if(result.length>0)
		{
			System.out.println(getLocalName()+": There is a Master Agent");

			//Master is already registered
			//Start Local Behavior

			//Set Service template to reflect role.
			agentServiceTemplate.setType("Local_Data_Agent");

			//Set Service template name to uniquely identify service
			agentServiceTemplate.setName(getLocalName()+"-Local_Data_Agent");

			//Start the start up behaviour of the agent
			addBehaviour(new localDataAgentStartUpBehaviour());

			events = new String[1];
			events[0] = "AddedAgents";
			
		}
		else
		{
			System.out.println(getLocalName()+": I will be the Master Agent");

			//Master is not already registered
			//Start Master Behavior
			
			//Service template already accurately reflects the role.

			//Set Service template name to uniquely identify service
			agentServiceTemplate.setName(getLocalName()+"-Master_Data_Agent");

			//Start the start up behaviour of the agent
			addBehaviour(new moveToMainContainerBehaviour());
			addBehaviour(new masterDataAgentStartUpBehaviour());

			events = new String[1];
			events[0] = "AddedContainers";
		}
	
		//Set template to reflect this agents Service using the Service Template
		agentDescription.addServices(agentServiceTemplate);
		
		try 
		{
			//Register this agent's Service
			DFService.register(this, agentDescription);
		}
		catch (FIPAException fe) 
		{
			fe.printStackTrace();
		}
		EventNotification(true,events);
		
	}

	protected void initialize()
	{
		//Used to register the FIPA_SL codec with this agent
		getContentManager().registerLanguage(new SLCodec(), FIPANames.ContentLanguage.FIPA_SL);
		
		//Used to register JADE Management Ontology with this agent
		getContentManager().registerOntology(JADEManagementOntology.getInstance());
	}
	
	protected void afterMove()
	{
		initialize();
	}
	
	protected void takeDown()
	{
		//Destrucion of agent goes here

		try 
		{
			//Deregister this agent's Service
			DFService.deregister(this);
		}
		catch (FIPAException fe) 
		{
			fe.printStackTrace();
		}
	}


	private void EventNotification(boolean register,String events[])
	{
		String eventAgentName;
		
		//Description used to register with the DF agent
		DFAgentDescription agentDescription = new DFAgentDescription();
		
		//Sets the name used in the description
		agentDescription.setName(getAID());
		
		//result is used to hold lists of agent descriptions returned from the search	
		DFAgentDescription result[]=new DFAgentDescription [0];
		
		//used to filter results from the search
		DFAgentDescription template = new DFAgentDescription();
				
		//Used to decide what kind of  service you are looking for
		ServiceDescription agentServiceTemplate = new ServiceDescription();
		
		//String description of the Service
		agentServiceTemplate.setType("Event_Agent");
	
		//Add your service template to the template
		template.addServices(agentServiceTemplate);
	
		try
		{
			//Search for the agent services matching the template
			result = DFService.search(this,template);
		}
		catch(FIPAException fe)
		{
			fe.printStackTrace();
		}
		if(result.length<=0)
		{
			System.out.println(getLocalName()+": There is not an Event Agent");
			createNewAgent("Local_Event_Agent","eventAgent");
			
			eventAgentName = "Local_Event_Agent";
		}
		else
		{
			eventAgentName = result[0].getName().getLocalName();
			System.out.println(getLocalName()+": There is an Event Agent");
		}
			
		jade.lang.acl.ACLMessage message;
		message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
		message.setLanguage("Event");
		message.setOntology("Event");
		message.addReceiver(new AID(eventAgentName, AID.ISLOCALNAME));
		String messageContent;
		
		if(register)
		{
			messageContent = "a:";
		}
		else
		{
			messageContent = "r:";
		}
				
		for(int i=0;i<events.length;i++)
		{
			message.setContent(messageContent+events[i]);
			send(message);
		}
				
				
	} 

	protected void createNewAgent(String agentName,String agentClassName)
	{
		//Creates a new Agent with the specified name, 
		//using the specified class,
		//and in the Main-Container.
		createNewAgent(agentName,agentClassName,"Main-Container",null);
	}

	protected void createNewAgent(String agentName,String agentClassName,String containerName,Object parameters[])
	{	
		//Creates a new Agent with the specified name, 
		//using the specified class,
		//and in the specified container.

		//Create a template for a new Agent
		CreateAgent ca = new CreateAgent();
		
		//Set the new Agent's name
		ca.setAgentName(agentName);
		
		//Set the new Agent's Class Name
		ca.setClassName(agentClassName);
		
		//Set the new Agent's Container Name
		//Null is because you don't need a transport address
		ca.setContainer(new ContainerID(containerName, null));
		if(parameters!=null)
		{
			for(int i=0;i<parameters.length;i++)
			{
				ca.addArguments(parameters[i]);
			}
		}
		//Create a new Action for the AMS 
		//using the AID of the ams and the template
		Action action = new Action(getAMS(), ca);
		
		//Construct a new message to hold your action
		jade.lang.acl.ACLMessage request = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.REQUEST);		
		
		//Address the message to the AMS
		request.addReceiver(getAMS());
		
		//Set the ontology so the AMS understands the request
		request.setOntology(JADEManagementOntology.getInstance().getName());
		
		//Set the Language so the AMS understands the request
		request.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
		
		//Set the Protocol so the AMS understands the request
		request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);

		try 
		{
			//Fill the Content slot of the message
			//using the defined language and ontology
			getContentManager().fillContent(request, action);
			
			//Send the message to the AMS
			send(request);

		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
	
	protected ArrayList <String> queryContainers()
	{
		

		//Create a new Action for the AMS
		Action action = new Action();
		
		//Set the Agent to be asked to perform the action
		action.setActor(getAMS());
		
		//Set the act to be requested
		action.setAction(new QueryPlatformLocationsAction());
		
		//Construct a new message to hold your action
		jade.lang.acl.ACLMessage request = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.REQUEST);

		//Address the message to the AMS
		request.addReceiver(getAMS());

		//Set the ontology so the AMS understands the request
		request.setOntology(JADEManagementOntology.getInstance().getName());
		
		//Set the Language so the AMS understands the request
		request.setLanguage(FIPANames.ContentLanguage.FIPA_SL);

		//Set the Protocol so the AMS understands the request
		request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);

		//ArrayList to hold the answer to the query
		ArrayList <String> temp=new ArrayList <String> (10);

		try 
		{
			//Fill the Content slot of the message
			//using the defined language and ontology
			getContentManager().fillContent(request, action);
			
			//Send the message to the AMS
			send(request);

			MessageTemplate language = MessageTemplate.MatchLanguage("fipa-sl");
				
			MessageTemplate ontology = MessageTemplate.MatchOntology("JADE-Agent-Management");
				
			MessageTemplate template = MessageTemplate.and(language,ontology);

			//Create a message and wait for it to be filled by the AMS 
			jade.lang.acl.ACLMessage msg = blockingReceive(template);

			while(!msg.getContent().substring(2,8).equals("result"))
			{
				msg = blockingReceive(template);
			}

			//Parse the Results using the specified ontology and language
			Result results= (Result)getContentManager().extractContent(msg);
			
			//Obtain an iterator to the List of Objects in results
			Iterator res_it= results.getItems().iterator();
			
			//While there is another element in the list
			while(res_it.hasNext())
			{
				//Convert it to a Location
				Location loc = (Location)res_it.next();
				
				//Add its name to the ArrayList
				temp.add(loc.getName());
			}
			//Now that we have the ArrayList to sort it
			Collections.swap(temp,temp.indexOf("Main-Container"),0);
					
			
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		//Return the ArrayList of Container Names
		return temp;	
	}

	private class moveToMainContainerBehaviour extends OneShotBehaviour
	{
		public void action()
		{
			WhereIsAgentAction amsLocation=new WhereIsAgentAction();
			amsLocation.setAgentIdentifier(getAMS());
			//Create a new Action for the AMS
			Action action = new Action();
			
			//Set the Agent to be asked to perform the action
			action.setActor(getAMS());
			
			//Set the act to be requested
			action.setAction(amsLocation);
		
			//Construct a new message to hold your action
			jade.lang.acl.ACLMessage request = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.REQUEST);
			//Address the message to the AMS
			request.addReceiver(getAMS());
			//Set the ontology so the AMS understands the request
			request.setOntology(JADEManagementOntology.getInstance().getName());
			
			//Set the Language so the AMS understands the request
			request.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
	
			//Set the Protocol so the AMS understands the request
			request.setProtocol(FIPANames.InteractionProtocol.FIPA_REQUEST);
			try 
			{
				//Fill the Content slot of the message
				//using the defined language and ontology
				getContentManager().fillContent(request, action);
			
				//Send the message to the AMS
				send(request);
				
				MessageTemplate language = MessageTemplate.MatchLanguage("fipa-sl");
				
				MessageTemplate ontology = MessageTemplate.MatchOntology("JADE-Agent-Management");
				
				MessageTemplate template = MessageTemplate.and(language,ontology);
				
				//Create a message and wait for it to be filled by the AMS 
				jade.lang.acl.ACLMessage msg = blockingReceive(template);
				while(!msg.getContent().substring(2,8).equals("result"))
				{
					msg = blockingReceive(template);
				}
				//Parse the Results using the specified ontology and language
				Result results = (Result) getContentManager().extractContent(msg);
				Iterator res_it= results.getItems().iterator();
				ContainerID cid = (ContainerID) res_it.next();
				ContainerID location = new ContainerID(String.valueOf(here()),null); 
				if(!(String.valueOf(cid).equals(String.valueOf(location.getName()))))
				{
					doMove(cid);
				}
			}	
			catch (Exception e)
			{
				e.printStackTrace();
			}

		}
	}
	private class masterDataAgentStartUpBehaviour extends OneShotBehaviour
	{
		public void action() 
		{
			System.out.println(getLocalName()+": Starting the Master Startup Behaviour");
			jadeContainer=queryContainers();
			for(int i=1;i<jadeContainer.size();i++)
			{
				String params[]=new String[2];
				params[0]="Move:";
				params[1]=jadeContainer.get(i);
				createNewAgent("local_"+jadeContainer.get(i),"dataAgent","Main-Container",(Object[])params);
			}
			startUp = new simulationStartUpBehaviour();
			addBehaviour(startUp);
			
		}
	}
	private class simulationStartUpBehaviour extends CyclicBehaviour
	{
		public void action() 
		{
			timeStamp=0;
			int numberOfBoats;
			int numberOfPorts;
			String runningStyle;
			String breechStyle;

			ArrayList <boatAndPortStorage> boats = new ArrayList <boatAndPortStorage> (10);
			ArrayList <boatAndPortStorage> ports = new ArrayList <boatAndPortStorage> (10);


			MessageTemplate language = MessageTemplate.MatchLanguage("Sim");
			MessageTemplate ontology = MessageTemplate.MatchOntology("Sim");
			MessageTemplate performative = MessageTemplate.MatchPerformative(jade.lang.acl.ACLMessage.INFORM);
			MessageTemplate template = MessageTemplate.and(language,ontology);
			template = MessageTemplate.and(template,performative);
			jade.lang.acl.ACLMessage msg = receive(template);

			if(msg!=null)
			{
				if(msg.getContent().substring(0,10).equals("Simulation"))
				{
					System.out.println("Simulation message received");
					String[] token = msg.getContent().substring(11).split(":");
    					if(token.length!=7)
					{
						System.out.println("Incorrect Simulation startup");
					}
					else
					{
						numberOfBoats = Integer.parseInt(token[0]);
						numberOfPorts = Integer.parseInt(token[2]);
						runningStyle = token[4];
						breechStyle = token[5];
						
						for(int i=0;i<numberOfBoats;i++)
						{
							boats.add(new boatAndPortStorage("Boat_"+(i+1),true,7000));
						}
						for(int i=0;i<numberOfPorts;i++)
						{
							ports.add(new boatAndPortStorage("Port_"+(i+1),false,70000));
						}
						String boatToken[] = token[1].split("=");
						if(boatToken!=null)
						{
							int boatNameIndex = 0;
							int boatCapacityIndex = 0;

							for(int i=0;i<boatToken.length;i++)
							{
								try
								{
									int temp=Integer.parseInt(boatToken[i]);
									if(boatCapacityIndex<numberOfBoats)
									{
										boats.get(boatCapacityIndex).setCapacity(temp);
										boatCapacityIndex++;
									}
								}
								catch(NumberFormatException nfe)
								{
									if(boatNameIndex<numberOfBoats)
									{
										boats.get(boatNameIndex).setName(boatToken[i]);
										boatNameIndex++;
									}	
								}
							}
						}
							
						String portToken[] = token[3].split("=");
						if(portToken!=null)
						{
							int portNameIndex = 0;
							int portCapacityIndex = 0;

							for(int i=0;i<portToken.length;i++)
							{
								try
								{
									int temp=Integer.parseInt(portToken[i]);
									if(portCapacityIndex<numberOfPorts)
									{
										ports.get(portCapacityIndex).setCapacity(temp);
										portCapacityIndex++;
									}
								}
								catch(NumberFormatException nfe)
								{
									if(portNameIndex<numberOfPorts)
									{
										ports.get(portNameIndex).setName(portToken[i]);
										portNameIndex++;
									}	
								}
							}
						}
						//System.out.println("The constructed ArrayList is...");
						//System.out.println(boats);
						//System.out.println(ports);
						assignWork(boats,ports);
						addBehaviour(new masterDataAgentControlBehaviour());
						removeBehaviour(startUp);
					}
				}	
			}
			else
			{
				block();
			}
		}
	}
	private void assignWork(ArrayList <boatAndPortStorage> boats,ArrayList <boatAndPortStorage> ports)
	{
		int averageNumberOfContainers = 0;
		int totalNumberOfContainers = 0;
		int numberOfAgents = 0;
		ArrayList <boatAndPortStorage> group = new ArrayList <boatAndPortStorage> (boats.size()+ports.size());
		String messageContent;
		jade.lang.acl.ACLMessage message;
		
		group.addAll(boats);
		group.addAll(ports);
	
		//result is used to hold lists of agent descriptions returned from the search	
		DFAgentDescription[] result=new DFAgentDescription [0];
			
		//used to filter results from the search
		DFAgentDescription template = new DFAgentDescription();
							
		//Used to decide what kind of  service you are looking for
		ServiceDescription agentServiceTemplate = new ServiceDescription();
							
		//String description of the Service
		agentServiceTemplate.setType("Local_Data_Agent");
							
		//Add your service template to the template
		template.addServices(agentServiceTemplate);
							
		try
		{
			//Search for the agent services matching the template
			result = DFService.search(this,template);	
		}
		catch(FIPAException fe)
		{
			fe.printStackTrace();
		}
		numberOfAgents = result.length;
		
		Collections.sort(group);
		System.out.println(group);

		for(int i=numberOfAgents;i>0;i--)
		{
			totalNumberOfContainers = 0;
			for(int j=0;j<group.size();j++)
			{
				totalNumberOfContainers=totalNumberOfContainers+group.get(j).getCapacity();
			}

			averageNumberOfContainers = totalNumberOfContainers / i;
			messageContent = "Startup:";
			int agentTotal=0;
			System.out.println("Average is :"+averageNumberOfContainers);
			System.out.println("Total is   :"+totalNumberOfContainers);
			System.out.println("Agents     :"+i);
			for(int j=0;j<group.size();j++)
			{
				if((agentTotal+group.get(j).getCapacity())<=averageNumberOfContainers)
				{
					agentTotal=agentTotal+group.get(j).getCapacity();
					messageContent = messageContent+group.get(j).getName()+"="+group.get(j).getType()+"="+group.get(j).getCapacity()+"=";
					group.remove(j);
					j=-1;
				}
			}
			messageContent = messageContent+":";
			//send the message to agent i
			if(messageContent.length()>10)
			{
				numberOfAgents++;
			}
			message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
			message.setLanguage("Sim");
			message.setOntology("Sim");
			message.addReceiver(new AID(result[(i-1)].getName().getLocalName(), AID.ISLOCALNAME));
			message.setContent(messageContent);
			send(message);
		}
	}

	private class boatAndPortStorage implements Comparable <boatAndPortStorage>
	{
		String name;
		boolean boat;
		int capacity;
		
		boatAndPortStorage()
		{
			name = "Default";
			boat = true;
			capacity = 7000;
		}
		boatAndPortStorage(String name,Boolean boat,Integer capacity)
		{
			if(name!=null)
			{
				this.name = name;
			}
			else
			{
				name = "Default";
			}
			if(boat!=null)
			{
				this.boat = boat;
			}
			else
			{
				boat = true;
			}
			if(capacity!=null)
			{
				this.capacity = capacity;
			}
			else
			{
				capacity = 7000;
			}
			
			
		}
		
		public void setName(String name)
		{
			this.name = name;
		}
		public void setType(boolean boat)
		{
			this.boat = boat;
		}
		public void setCapacity(int capacity)
		{
			this.capacity = capacity;
		}
		public String getName()
		{
			return name;
		}
		public boolean getType()
		{
			return boat;
		}
		public int getCapacity()
		{
			return capacity;
		}
		public int compareTo(boatAndPortStorage object1)
		{
    			int anotherCapacity = object1.getCapacity();  
    			return anotherCapacity - this.capacity;    
  		}

		public String toString()
		{
			String output = "\n";
			output=output+"Name is : "+name+"\n";
			output=output+"Boat    : "+boat+"\n";
			output=output+"Capacity: "+capacity;
			return output;
		}
		
	}
		

	private class localDataAgentStartUpBehaviour extends OneShotBehaviour
	{
		public void action() 
		{
			System.out.println(getLocalName()+": Starting the Local Startup Behaviour");
			if(arguments.length>1)
			{
				System.out.println(getLocalName()+": There is more than 1 argument");
				if("Move:".equals(String.valueOf(arguments[0])))
				{
					System.out.println(getLocalName()+": The Move command was issued");
					addBehaviour(new localDataAgentCycleBehaviour());
					doMove(new ContainerID(String.valueOf(arguments[1]), null));
				}
			}
		}
	}
	
	private class localDataAgentCycleBehaviour extends CyclicBehaviour
	{
		
		public void action() 
		{
			int numberOfBoats;
			int numberOfPorts;
			String runningStyle;
			String breechStyle;
			


			String messageContent;

			ArrayList <boatAndPortStorage> boats = new ArrayList <boatAndPortStorage> (10);
			ArrayList <boatAndPortStorage> ports = new ArrayList <boatAndPortStorage> (10);

			MessageTemplate language = MessageTemplate.MatchLanguage("Sim");
			MessageTemplate ontology = MessageTemplate.MatchOntology("Sim");
			MessageTemplate performative = MessageTemplate.MatchPerformative(jade.lang.acl.ACLMessage.INFORM);
			MessageTemplate template = MessageTemplate.and(language,ontology);
			template = MessageTemplate.and(template,performative);
			jade.lang.acl.ACLMessage msg = receive(template);

			if(msg!=null)
			{
				if(msg.getContent().substring(0,7).equals("Startup"))
				{
					jade.lang.acl.ACLMessage message;
					System.out.println("Simulation message received");
					String[] token = msg.getContent().substring(8).split(":");
					token = token[0].split("=");
					System.out.println(token.length);
					//okay I have the work assignment
					//Now I need to:
					//create the messages to:
					//start up a sleep agent
					//start up a send agent
					//start up a receive agent
					//and then send it.

					for(int i=0;i<token.length;i+=3)
					{
						sleepAgentName = "Sleep_"+String.valueOf(arguments[1])+"_"+token[i];
						sendAgentName = "Send_"+String.valueOf(arguments[1])+"_"+token[i];
						receiveAgentName = "Receive_"+String.valueOf(arguments[1])+"_"+token[i];

						//request Agent creation
						createNewAgent(sleepAgentName,"SleepAgent",String.valueOf(arguments[1]),null);
						createNewAgent(sendAgentName,"SendAgent",String.valueOf(arguments[1]),null);
						createNewAgent(receiveAgentName,"ReceiveAgent",String.valueOf(arguments[1]),null);
						
						
						int maxX=10;
						int maxZ=7;
						int maxY=(Integer.parseInt(token[i+2])/(maxX*maxZ))*2;
						
						messageContent="";
						messageContent=messageContent+maxX+":";
						messageContent=messageContent+maxY+":";
						messageContent=messageContent+maxZ+":";
						messageContent=messageContent+token[i+2]+":";
						messageContent=messageContent+token[i]+":";
						messageContent=messageContent+"0:";
						
						//Send startup message
						message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
						message.setLanguage("English");
						message.setOntology("Container-startup-ontology");
						message.addReceiver(new AID(sleepAgentName, AID.ISLOCALNAME));
						message.addReceiver(new AID(sendAgentName, AID.ISLOCALNAME));
						message.addReceiver(new AID(receiveAgentName, AID.ISLOCALNAME));
						message.setContent(messageContent);
						send(message);
						addBehaviour(new localDataAgentControlBehaviour());
						removeBehaviour(this);
					}
				}
    					
			}
			else
			{
				block();
			}	
		}
	}		

	private class masterDataAgentControlBehaviour extends CyclicBehaviour
	{
		ArrayList <String> nameOfAgent = new ArrayList <String> (numberOfAgents);
		jade.lang.acl.ACLMessage message;
		int i=0;

		public void action() 
		{
			i++;
			if(nameOfAgent.size()==numberOfAgents)
			{
				timeStamp++;
				//send the message
				message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
				message.setLanguage("English");
				message.setOntology("Container-continue-ontology");
				for(int i=0;i<nameOfAgent.size();i++)
				{
					message.addReceiver(new AID(nameOfAgent.get(i), AID.ISLOCALNAME));
				}
				message.setContent(String.valueOf(timeStamp));
				nameOfAgent.clear();
				doWait(3000);
			}
			message = receive();
			if (message != null) 
			{
				if(message.getOntology().equals("Container-continue-ontology"))
				{
					if(!nameOfAgent.contains(message.getSender().getLocalName()))
					{
						nameOfAgent.add(message.getSender().getLocalName());
		
					}
				}
				
				
			}
			if((i%1)==0)
			{
				System.out.println(nameOfAgent);
			}
			
		}
	}
	private class localDataAgentControlBehaviour extends CyclicBehaviour
	{
		jade.lang.acl.ACLMessage message;
		int i=0;
		String messageContent;

		public void action() 
		{
			message = receive();
			if (message != null) 
			{
				messageContent = message.getContent();
				if(message.getOntology().equals("Container-continue-ontology"))
				{
					if(message.getContent().equals("Done"))
					{
						//result is used to hold lists of agent descriptions returned from the search	
						DFAgentDescription[] result=new DFAgentDescription [0];
				
						//used to filter results from the search
						DFAgentDescription template = new DFAgentDescription();
							
						//Used to decide what kind of  service you are looking for
						ServiceDescription agentServiceTemplate = new ServiceDescription();
									
						//String description of the Service
						agentServiceTemplate.setType("Master_Data_Agent");
								
						//Add your service template to the template
						template.addServices(agentServiceTemplate);
								
						try
						{
							//Search for the agent services matching the template
							result = DFService.search(myAgent,template);	
						}
						catch(FIPAException fe)
						{
							fe.printStackTrace();
						}
						message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
						message.setLanguage("English");
						message.setOntology("Container-continue-ontology");
						message.addReceiver(result[0].getName());
						message.setContent(messageContent);
						send(message);
					}
					else
					{
						message = new jade.lang.acl.ACLMessage(jade.lang.acl.ACLMessage.INFORM);
						message.setLanguage("English");
						message.setOntology("Container-continue-ontology");
						message.addReceiver(new AID(sendAgentName, AID.ISLOCALNAME));
						message.addReceiver(new AID(receiveAgentName, AID.ISLOCALNAME));
						message.addReceiver(new AID(sleepAgentName, AID.ISLOCALNAME));
						message.setContent(messageContent);
						send(message);
					}
					
				}
				
			}
			
		}
	}

}
	
	
	

